package com.wontube.client.extension.io.protocol;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.wontube.client.extension.utils.StringUtils;
import com.wontube.client.io.IObjectProtocol;
import com.wontube.client.utils.Base64;

/**
 * @author yuechao
 *
 */
public final class HessianObjectProtocol implements IObjectProtocol {
	/*
	 * @see client.io.IObjectProtocol#toProtoString(java.lang.Object)
	 */
	@Override
	public String toProtoString(Object value) {
		if (value == null) {
			return "";
		}

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		HessianOutput ho = new HessianOutput(os);
		try {
			ho.writeObject(value);
			byte[] buffer = os.toByteArray();
			String result = Base64.encode(buffer);
			return result;
		} catch (IOException e) {
		} finally {
			try {
				ho.close();
			} catch (IOException e) {
			}
		}

		return "";
	}

	/*
	 * @see client.io.IObjectProtocol#toObject(java.lang.String,
	 * java.lang.reflect.Type)
	 */
	@Override
	public Object toObject(String value, Type type) {
		if (StringUtils.isNullOrEmpty(value)) {
			return null;
		}

		byte[] buffer = Base64.decode(value);
		ByteArrayInputStream is = new ByteArrayInputStream(buffer);
		HessianInput hi = new HessianInput(is);
		Object result = null;
		try {
			result = hi.readObject();
		} catch (IOException e) {
		} finally {
			hi.close();
		}

		return result;
	}
}
